package com.bjfl.saleManager.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import com.bjfl.bean.StorageBean;
import com.log.LatteLogger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SuppressLint({"SimpleDateFormat", "DefaultLocale"})
public class LogUtil {
    public static Context context;
    public static final String CODE_LOG = "CodeLog";
    public static final String KEY_LOG = "KeyLog";
    public static final String ELELOCK_LOG = "EleLockLog";
    public static final String SHIPE_MENT_LOG = "ShipeMentLog";
    public static final String POCKET_LOG = "PocketLog";
    public static final String PRIZE_LOG = "PrizeLog";
    public static final String COIN_LOG = "CoinLog";
    public static final String ACCEPT_CASH_LOG = "AcceptCashLog";
    public static final String MOTOR_LOG = "MotorLog";
    public static final String CSM_LOG = "CSMLog";
    public static final String GOODS_DEVICE_LOG = "GoodsDeviceLog";
    public static final String EXCEPTION_LOG = "ExceptionLog";

    public static void writeCodeLog(String log) {
        writeLog(log, "CodeLog");
    }

    public static void writeKeyLog(String log) {
        writeLog(log, "KeyLog");
    }

    public static void writeEleLockLog(String log) {
        writeLog(log, "EleLockLog");
    }

    public static void writeShipeMentInfo(String log) {
        writeLog(log, "ShipeMentLog");
    }

    public static void writePocketInfo(String log) {
        writeLog(log, "PocketLog");
    }

    public static void writePrizeLog(String log) {
        writeLog(log, "PrizeLog");
    }

    public static void writeCoinLog(String log) {
        writeLog(log, "CoinLog");
    }

    public static void writeAcceptCashLog(String bytesToHexString) {
        writeLog(bytesToHexString, "AcceptCashLog");
    }

    public static void writeMotorOperateLog(String bytesToHexString) {
        writeLog(bytesToHexString, "MotorLog");
    }

    public static void writeCSMLog(String bytesToHexString) {
        writeLog(bytesToHexString, "CSMLog");
    }

    public static void writeGoodsDeviceLog(String str) {
        writeLog(str, "GoodsDeviceLog");
    }

    public static void writeCoinAcceptorInfo(String bytesToHexString) {
        writeLog(bytesToHexString, "CoinAcceptorLog");
    }

    public static void WriteUPSInfo(String bytesToHexString) {
        writeLog(bytesToHexString, "UPSLog");
    }

    public static void writePrintInfo(String bytesToHexString) {
        writeLog(bytesToHexString, "PrintLog");
    }

    public static void writeExceptionLog(String logMsg) {
        writeLog(logMsg, "ExceptionLog");
    }


    public static void deleteFile(String dirStr) {
        try {
            String dirPath = generateDir(dirStr);
            int day = 180;
            Calendar cal = Calendar.getInstance();

            cal.add(Calendar.DAY_OF_YEAR, -day);
            String Strday = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
            File root = new File(dirPath);
            if (root.exists()) {
                File[] files = root.listFiles();
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFile(file.getAbsolutePath());
                    } else if (file.getName().length() >= 10) {
                        String MinFileName = file.getName().substring(0, 10).replace("_", "").trim();
                        boolean isDel = Long.parseLong(MinFileName) < Long.parseLong(Strday);
                        if (isDel) {
                            File deletefile = new File(dirPath + File.separator + file.getName());
                            deletefile.delete();
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.getMessage();
        }
    }

    private static final String EXTENSION = ".txt";

    private static final ExecutorService excutor = Executors.newFixedThreadPool(4);

    public static void writeLog(final String logMsg, final String dirName) {
        excutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String fileName = generateFileName(dirName);
                    FileOutputStream fOut = null;
                    fOut = new FileOutputStream(fileName, true);
                    OutputStreamWriter osw = new OutputStreamWriter(fOut);
                    osw.append(generateTimeStr() + "  " + logMsg + "\r\n");
                    osw.flush();
                    osw.close();
                    fOut.flush();
                    fOut.close();
                    LatteLogger.d("Path", "writeLog success");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    writeExceptionLog(ex.getMessage());
                }

            }
        });

    }

    private static String fileName;

    private static String generateFileName(String dirName) {
        String path = getPrePath();
        //      "/mnt/extsd/type/yy_MM_dd.txt"
        String dateStr = new SimpleDateFormat("yyyy_MM_dd").format(new java.util.Date());
        if (!TextUtils.isEmpty(path)) {
            File directory = new File(path + File.separator + dirName);
            directory.mkdirs();
            fileName = path + File.separator + dirName + File.separator
                    + dateStr + EXTENSION;
            LatteLogger.d("PathExt", fileName);
        }
        return fileName;
    }

    private static String generateDir(String dirName) {
        String dirPath = "";
        String path = getPrePath();
        if (!TextUtils.isEmpty(path)) {
            dirPath = path + File.separator + dirName;
        }
        return dirPath;
    }

    private static String getPrePath() {
        String path = "";

        List<StorageBean> storageBeanList = StorageUtils.getStorageData(context);
        for (StorageBean pathBean : storageBeanList) {
            if (pathBean.getRemovable()) {
                if (pathBean.getMounted().equalsIgnoreCase("mounted")) {
                    LatteLogger.i("extPath", pathBean.getPath());
                    if (pathBean.getPath().contains("ext")) {
                        path = pathBean.getPath();
                        break;
                    }
                }

            } else {
                path = pathBean.getPath();
                LatteLogger.i("innerPath", pathBean.getPath());
                break;
            }
        }
        return path;
    }


    private static String generateTimeStr() {
        Date curDate = new Date(System.currentTimeMillis());
        SimpleDateFormat formatter1 = new SimpleDateFormat("HH:mm:ss:SSS");
        String timeStr = formatter1.format(curDate);

        return timeStr;
    }


    @SuppressLint({"DefaultLocale"})
    public static String bytesToHexString(byte[] src, int size) {
        String ret = "";
        if ((src == null) || (size <= 0)) {
            return null;
        }
        for (int i = 0; i < size; i++) {
            String hex = Integer.toHexString(src[i] & 0xFF);
            if (hex.length() < 2) {
                hex = "0" + hex;
            }
            ret = ret + hex;
        }
        return ret.toUpperCase();
    }
}
